#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

//int code = 0;
int main()
{
    pid_t id = fork();
    if (id < 0)
    {
        perror("fork");
        exit(1); 
    }
    else if (id == 0)
    {
        //子进程
        int cnt = 5;
        while (cnt)
        {
            printf("cnt: %d, 我是子进程, pid: %d, ppid : %d\n", cnt, getpid(), getppid());
            sleep(1);
            cnt--;
        }
        //code = 15;
        exit(0);
    }
    else
    {
        //父进程
        printf("我是父进程, pid: %d, ppid: %d\n", getpid(), getppid());
        int status = 0;
        pid_t ret = waitpid(id, &status, 0); //阻塞式的等待
        if (ret > 0)
        {   
            int signal_number = status & 0x7F;
            int exit_code = (status >> 8) & 0xFF;

            printf("等待子进程改变状态, ret: %d, 子进程收到的信号编号: %d, 子进程退出码: %d\n", ret, signal_number, exit_code);
            //printf("code: %d\n", code);
        }
    }
}
